﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Data.Entity.Core.Common.CommandTrees;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using WeatheRx.Data;

namespace WeatheRx.Managers
{
    public interface IJobManager
    {
        Job Get(int jobId);

        void Store(Job job);
    }

    public class JobManager : IJobManager
    {
        private readonly IWorkOrderManager workOrderManager;

        public JobManager(IWorkOrderManager wo)
        {
            workOrderManager = wo;
        }

        public JobManager()
        {
            workOrderManager = new WorkOrderManager();
        }

        public Job Get(int jobId)
        {
            Job result;
            using (var db = new HWAPEntities())
            {
                result = db.Jobs.FirstOrDefault(x => x.JobId == jobId);
            }

            return result;
        }

        public void Store(Job job)
        {
            if (job.JobId > 0)
                Update(job);
            else
            {
                Add(job);
            }
        }

        private void Add(Job job)
        {
            using (var db = new HWAPEntities())
            {
                db.Jobs.Add(job);
                db.SaveChanges();
            }
            workOrderManager.StoreRange(job.WorkOrders.ToList());
        }

        private void Update(Job job)
        {
            using (var db = new HWAPEntities())
            {
                var firstOrDefault = db.Jobs.FirstOrDefault(x => x.JobId == job.JobId);
                if (firstOrDefault == null)
                {
                    db.Jobs.Add(job);
                }
                else
                {
                    Mapper.Map(job, firstOrDefault);
                }
                db.SaveChanges();
            }
        }
    }
}